<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/4
 * Time: 14:40
 */

namespace app\models;

use yii;
use yii\db\Query;

class CouponModal
{
    public $table;

    public function __construct()
    {
        $this->table = yii::$app->db->tablePrefix . 'coupon';
    }

    public function all($filed, $where)
    {
        $db = new Query();
        $info = $db->select($filed)->from($this->table)->where($where)->all();
        $list = $this->couponList();
        foreach ($info as $k => $v) {
            foreach ($list as $v2) {
                if ($v['coupon_id'] == $v2['id']) {
                    $info[$k]['detail'] = $v2;
                }
            }
        }
        return $info ? $info : false;

    }

    public function one($filed, $where)
    {
        $db = new Query();
        $info = $db->select($filed)->from($this->table)->where($where)->one();
        if ($info) {
            $list = $this->couponList();
            foreach ($list as $v) {
                if ($v['id'] == $info['coupon_id']) {
                    $info['detail'] = $v;
                    return $info;
                }
            }
            return $info;
        }

        return false;
    }

    public function couponList()
    {
        $db = new Query();
        return $db->select('*')->from('jingsourcing_coupon_list')->all();
    }

    /**
     * 注册送一张优惠券
     * 服务费,拍照,设计费用
     */
    public function register50($user_id)
    {
        $this->generateCoupon('S', 1, $user_id);
        $this->generateCoupon('D', 2, $user_id);
        $this->generateCoupon('P', 3, $user_id);
    }

    /**生成
     * @param $type
     * @param $couponId
     * @param $user_id
     */
    public function generateCoupon($type, $couponId, $user_id)
    {
        $number = date('ymd') . substr(md5(time() . $user_id . rand(0, 100)), 0, 4);
        $data['number_no'] = strtoupper($type . $number);
        $data['coupon_id'] = $couponId;
        $data['user_id'] = $user_id;
        $data['time'] = time();
        $data['expire_time'] = time() + 24 * 3600 * 360;
        try {
            yii::$app->db->createCommand()->insert($this->table, $data)->execute();
        } catch (\Exception $e) {
            yii::error($e->getMessage());
        }

    }
}